package result

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mylog"
	"wrblog-api-go/pkg/status"
)

type Rows struct {
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
	Rows  any    `json:"rows"`
	Total int64  `json:"total"`
}

func PageRes(row any, total int64, err error) *Rows {
	if err != nil {
		return PageFail(err)
	} else {
		return Page(row, total)
	}
}

// Page 成功返回
func Page(row any, total int64) *Rows {
	// 默认返回数据格式的结构体
	defaultData := &Rows{
		Code:  status.OK,
		Msg:   "ok",
		Rows:  nil,
		Total: 0,
	}
	if row != nil {
		defaultData.Rows = row
	}
	if total != 0 {
		defaultData.Total = total
	}
	return &Rows{Code: defaultData.Code, Msg: defaultData.Msg, Rows: defaultData.Rows, Total: defaultData.Total}
}

// PageFail 失败返回
func PageFail(err error) *Rows {
	var e *errs.Error
	if errors.As(err, &e) {
		mylog.MyLog.Error(e.Msg)
		return PageWrap(e.Code, e.Msg)
	} else {
		// 默认返回数据格式的结构体
		defaultData := &Rows{
			Code:  status.InternalServerError,
			Msg:   "error",
			Rows:  nil,
			Total: 0,
		}
		if e.Msg != "" {
			defaultData.Msg = e.Msg
		}
		mylog.MyLog.Errorf("系统错误！%s\n%s", e.Msg, e.Stack)
		return &Rows{Code: defaultData.Code, Msg: defaultData.Msg, Rows: defaultData.Rows, Total: defaultData.Total}
	}
}

// PageWrap 自定义返回
func PageWrap(code int, msg string) *Rows {
	// 默认返回数据格式的结构体
	defaultData := &Rows{
		Code:  status.NoContent,
		Msg:   "wrap",
		Rows:  nil,
		Total: 0,
	}
	if code != 0 {
		defaultData.Code = code
	}
	if msg != "" {
		defaultData.Msg = msg
	}
	mylog.MyLog.Error(defaultData.Msg)
	return &Rows{Code: defaultData.Code, Msg: defaultData.Msg, Rows: defaultData.Rows, Total: defaultData.Total}
}

// Json 序列化返回
func (row *Rows) Json(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, row)
	ctx.Abort()
}
